//
//  MyViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/11/30.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "MyViewController.h"
#import "AvatarView.h"
#import "MyTableViewCell.h"
#import "MyInfoViewController.h"
#import "AboutUsViewController.h"
#import "FeedbackViewController.h"
#import "FaceDiscernHistoryViewController.h"
#import "BindDeviceViewController.h"
#import "UnBindDeviceApi.h"

@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource>

/** 头像视图 **/
@property(nonatomic,strong) AvatarView *avatarView;

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSArray *dataSource;
@property(nonatomic,strong) NSArray *imageDataSource;


@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self updateAvatarAndNickName];
}

#pragma mark --- 点击事件
- (void)didClickAvatarView
{
    MyInfoViewController *vc = [MyInfoViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark --- 事件处理
- (void)updateAvatarAndNickName
{
    [self.avatarView.avatarImageView sd_setImageWithURL:[NSURL URLWithString:EXRACT_OBJECT(IMAGE)] placeholderImage:imageWithName(@"icon_head")];
    self.avatarView.nicknameLabel.text = EXRACT_OBJECT(NICKNAME);
}

// 解绑设备
- (void)unbindDevice
{
    UnBindDeviceApi *api = [[UnBindDeviceApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID)}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseJSONObject;
        [SVProgressHUD showSuccessWithStatus:dict[@"errmsg"]];
//        if ([dict[@"old_admin_uid"] isEqualToString:EXRACT_OBJECT(UID)]) // 原本是管理员需要操作群
//        {
//            if (EXRACT_OBJECT(GID))
//            {
//                if ([dict[@"admin_uid"] intValue] == 0)// 没有其他管理员，移除群组
//                {
//                    [self removeGroup];
//                }
//                else
//                {
//                    [self transferGroupWithAdminUID:dict[@"admin_uid"]];
//                }
//            }
//        }
//        else  // 原本不是管理员需要退出群
//        {
//            [self exitGroup];
//        }
        

        
        SAVE_OBJECT(@"0", DEVICEID);
        BindDeviceViewController *vc = [BindDeviceViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } failure:nil];
}
// 退出群组
- (void)exitGroup
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
        EMError *error = nil;
        [[EMClient sharedClient].groupManager leaveGroup:EXRACT_OBJECT(GID) error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                
            }
            else
            {
                
            }
        });
    });
}

// 移除群组
- (void)removeGroup
{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
        EMError *error = [[EMClient sharedClient].groupManager destroyGroup:EXRACT_OBJECT(GID)];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                // 群主无法退出群只能解散群
                [[EMClient sharedClient].groupManager destroyGroup:EXRACT_OBJECT(GID)];
            }
            else
            {
                
            }
        });
    });
}
// 改变群主
- (void)transferGroupWithAdminUID:(NSString *)uid
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
        EMError *error = nil;
        [[EMClient sharedClient].groupManager updateGroupOwner:EXRACT_OBJECT(UID) newOwner:uid error:&error];
//        EMError *error = [[EMClient sharedClient].groupManager destroyGroup:EXRACT_OBJECT(GID)];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                
            }
            else
            {
                
            }
        });
    });
}


#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.dataSource[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(150);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *cell = [MyTableViewCell dequeueReusableWithTableView:tableView];
    NSArray *titleArray = self.dataSource[indexPath.section];
    NSArray *imageArray = self.imageDataSource[indexPath.section];
    cell.iconImageView.image = imageWithName(imageArray[indexPath.row]);
    cell.titleLabel.text = titleArray[indexPath.row];
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                if ([EXRACT_OBJECT(DEVICEID) isEqualToString:@"0"] || !EXRACT_OBJECT(DEVICEID)) // 没有设备
                {
                    BindDeviceViewController *vc = [BindDeviceViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
             
                }
                else
                {
                    [[AlertViewManager shareManager] initWithTitle:@"提示" message:@"您确定要解绑当前设备？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                        if (buttonIndex == 1)
                        {
                            [self unbindDevice];
                        }
                    }];
                }

            }
                break;
            case 1:
            {
                FaceDiscernHistoryViewController *vc = [FaceDiscernHistoryViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2:
            {
                
            }
                break;
                
            default:
                break;
        }
    }
    else if (indexPath.section == 1)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                FeedbackViewController *vc = [FeedbackViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1:
            {
                AboutUsViewController *vc = [AboutUsViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;

                
            default:
                break;
        }
    }
}

#pragma mark --- 懒加载
- (AvatarView *)avatarView
{
    if(!_avatarView)
    {
        UIView *superView = self.view;
        _avatarView = [[AvatarView alloc]init];
        [superView addSubview:_avatarView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickAvatarView)];
        [_avatarView addGestureRecognizer:tap];
    }
    return _avatarView;
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        [superView addSubview:_tableView];
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (NSArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = @[@[@"绑定新设备",@"设备人脸识别记录",@"使用帮助"],@[@"意见反馈",@"关于我们"]];
    }
    return _dataSource;
}

- (NSArray *)imageDataSource
{
    if (!_imageDataSource)
    {
        _imageDataSource = @[@[@"icon_new equipment",@"icon_face",@"icon_help"],@[@"icon_ideo",@"icon_flock"]];
    }
    return _imageDataSource;
}


#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(170));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.mas_equalTo(px1920Height(350));
        make.width.mas_equalTo(superView);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.avatarView.mas_bottom).with.offset(px1920Height(75));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];

}


#pragma mark --- 设置导航栏
- (void)setNavigationStyle
{
    [self setLeftButtonImage:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
